package com.neusoft.neuiotms.dcom.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.neusoft.bizcore.auth.common.bean.UserBean;
import com.neusoft.bizcore.web.dto.result.PageResultDTO;
import com.neusoft.bizcore.web.dto.result.ResultDTO;
import com.neusoft.bizcore.web.dto.result.ResultListDTO;
import com.neusoft.bizcore.web.exception.UnitedException;
import com.neusoft.bizcore.web.support.Searchable;
import com.neusoft.neuiotms.dcom.dto.OperationSupportWeeklyDTO;
import com.neusoft.neuiotms.dcom.service.OperationSupportWeeklyService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

@Api(tags = "运维支撑服务周报管理")
@RestController
@Slf4j
@RequestMapping(value = "/api/w/operationSupportWeekly")
public class OperationSupportWeeklyController {

    @Autowired
    private OperationSupportWeeklyService operationSupportWeeklyService;

    @ApiOperation("查询所有运维支撑服务周报")
    @GetMapping
    public ResultListDTO<OperationSupportWeeklyDTO> index(final Searchable searchable, final UserBean userBean) {
        return ResultListDTO.success(this.operationSupportWeeklyService.index(searchable, userBean));
    }

    @ApiOperation("分页查询所有运维支撑服务周报")
    @GetMapping("/p")
    public PageResultDTO<OperationSupportWeeklyDTO> search(final Pageable pageable, final Searchable searchable,
            final UserBean userBean) {
        return PageResultDTO.success(this.operationSupportWeeklyService.page(searchable, pageable, userBean));
    }

    @ApiOperation("创建运维支撑服务周报")
    @PostMapping("")
    public ResultDTO<OperationSupportWeeklyDTO> create(@RequestBody final OperationSupportWeeklyDTO dto) {
        return ResultDTO.success(this.operationSupportWeeklyService.create(dto));
    }

    @ApiOperation(value = "修改运维支撑服务周报")
    @PutMapping("/{id}")
    public ResultDTO<OperationSupportWeeklyDTO> update(@PathVariable final Long id,
            @RequestBody final OperationSupportWeeklyDTO dto) {
        return ResultDTO.success(this.operationSupportWeeklyService.update(id, dto));
    }

    @ApiOperation("运维支撑服务周报详情")
    @GetMapping("/{id}")
    public ResultDTO<OperationSupportWeeklyDTO> details(@PathVariable final Long id) {
        return ResultDTO.success(this.operationSupportWeeklyService.detail(id));
    }

    @ApiOperation("删除运维支撑服务周报")
    @DeleteMapping("/{id}")
    public ResultDTO<Void> delete(@PathVariable final Long id) {
        this.operationSupportWeeklyService.delete(id);
        return ResultDTO.success();
    }

    @ApiOperation("导入运维支撑服务周报")
    @PostMapping("/upload")
    public ResultDTO<Void> upload(@RequestParam("file") final MultipartFile file, final UserBean user) {
        this.operationSupportWeeklyService.upload(file, user);
        return ResultDTO.success();
    }

    @ApiOperation("导出运维支撑服务周报")
    @GetMapping(value = "/export")
    public void download(final Searchable searchable, final Pageable pageable,
            final HttpServletResponse response, final UserBean userBean) {

        final Workbook workbook = this.operationSupportWeeklyService.export(searchable, userBean);
        OutputStream out = null;
        try {
            out = response.getOutputStream();
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-disposition",
                    String.format("attachment; filename=%s",
                            URLEncoder.encode("运维支撑服务周报导出" + LocalDateTime.now() + ".xlsx", "UTF-8")));
            workbook.write(out);
            out.flush();
        } catch (final Exception e) {
            OperationSupportWeeklyController.log.error("运维支撑服务周报导出失败", e);
        } finally {
            try {
                out.close();
            } catch (final IOException e) {
                OperationSupportWeeklyController.log.error("运维支撑服务周报导出关闭流失败", e);
            }
        }
    }

    @ApiOperation("运维周报统计")
    @GetMapping("/stats")
    public ResultDTO<?> todayStats() {
        final Map<String, Long> result = this.operationSupportWeeklyService.reportStats();
        return ResultDTO.success(result);
    }

    @ApiOperation("下载导入模版")
    @GetMapping("/template")
    public void downloadTpl(final HttpServletResponse response, final UserBean user) {

        final Workbook workbook = this.operationSupportWeeklyService.template(user);
        OutputStream out = null;
        try {
            out = response.getOutputStream();
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-disposition",
                    String.format("attachment; filename=%s",
                            URLEncoder.encode(workbook.getSheetName(0) + ".xlsx", "UTF-8")));
            workbook.write(out);
            out.flush();
        } catch (final Exception e) {
            OperationSupportWeeklyController.log.error("运维支撑周报下载模板异常", e);
        } finally {
            try {
                out.close();
            } catch (final IOException e) {
                OperationSupportWeeklyController.log.error("运维支撑周报下载模板异常", e);
            }
        }
    }

    @ApiOperation("导入")
    @PostMapping("/import")
    public ResultDTO<?> importTpl(@RequestParam("file") final MultipartFile file, final UserBean user) {
        try {
            this.operationSupportWeeklyService.importExcel(file.getInputStream(), user);
        } catch (final IOException e) {
            e.printStackTrace();
            throw new UnitedException(e.getMessage());
        }
        return ResultDTO.success();
    }

    @ApiOperation("周报统计报表")
    @GetMapping("/stats/report")
    public PageResultDTO<Map<String, Object>> reportStats(final Pageable pageable,
            @RequestParam(required = false) final String username,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") final Date start,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") final Date end) {
        final Page<Map<String, Object>> result =
                this.operationSupportWeeklyService.report(pageable, username, start, end);
        return PageResultDTO.success(result);
    }

    @ApiOperation("导出周报统计")
    @GetMapping(value = "/stats/export")
    public void exportStats(@RequestParam(required = false) final String username,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") final Date start,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") final Date end,
            final HttpServletResponse response) {

        final Workbook workbook = this.operationSupportWeeklyService.exportReport(username, start, end);
        OutputStream out = null;
        try {
            out = response.getOutputStream();
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-disposition",
                    String.format("attachment; filename=%s",
                            URLEncoder.encode("周报统计导出" + LocalDateTime.now() + ".xlsx", "UTF-8")));
            workbook.write(out);
            out.flush();
        } catch (final Exception e) {
            OperationSupportWeeklyController.log.error("周报统计导出失败", e);
        } finally {
            try {
                out.close();
            } catch (final IOException e) {
                OperationSupportWeeklyController.log.error("周报统计导出关闭流失败", e);
            }
        }
    }

    @ApiOperation("运维周报提醒测试")
    @GetMapping("/notice/test")
    public ResultDTO<?> noticeTest() {
        this.operationSupportWeeklyService.checkReportNotice();
        return ResultDTO.success();
    }

}
